package com.lenovo.mso2o.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.base.InjectableDialogFragment;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.util.AppHelper;
import com.lenovo.framework.util.DLog;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.OrderAction;
import com.lenovo.mso2o.entity.OrderUpdatingRequest;
import com.lenovo.mso2o.entity.g.AutoSignOrder;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.service.AutoSignService;
import com.lenovo.mso2o.ui.MainActivity;
import com.lenovo.mso2o.ui.SignInCameraActivity;
import com.lenovo.mso2o.ui.WebActivity;
import com.lenovo.mso2o.ui.adapter.AutoSignAdapter;
import com.lenovo.mso2o.util.Utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by lenovo on 2016/3/5.
 */
public class AutoSignFragment extends InjectableDialogFragment implements AutoSignAdapter.SignRecyclerItemClickListener {
    public static final String TAG = "AutoSignFragment";
    public static List<AutoSignOrder> mSignOrders;
    private static AutoSignFragment autoSignFragment;
    private static final int REQUEST_PERMISSION = 0x3e;
    public static LatLng signedLatLng;
    private HashMap<String, Runnable> permissionCallbacks = new HashMap<>();
    @Bind(R.id.recycler_auto_sign_list)
    RecyclerView mAutoSignView;
    @Bind(R.id.auto_sign_bottom_upload_photo)
    Button btPhotoUpload;
    @Bind(R.id.layout_autosign_outside_recycler)
    RelativeLayout layoutSign;
    public static long currentTime;

    public AutoSignFragment() {
    }
    /**
     * request permission
     *
     * @param permission
     * @param callback
     */
    private void requestPermission(String permission, Runnable callback) {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(ContextManager.context(), permission)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    permission)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                DLog.w("login:", "setting needed!");
                new Handler(Looper.getMainLooper()).post(callback);
            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{permission}, REQUEST_PERMISSION);
                permissionCallbacks.put(permission, callback);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }else{
            new Handler(Looper.getMainLooper()).post(callback);
        }
    }

    @OnClick(R.id.auto_sign_bottom_upload_photo)
    public void clickUploadPhoto(){
        //附件上传
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), AppHelper.packageName());
        // Create the storage directory if it does not exist
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        final File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        Uri imageUri = Uri.fromFile(file);
        final Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        PackageManager pm = getActivity().getPackageManager();
        if (pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
            requestPermission(Manifest.permission.CAMERA, new Runnable() {
                @Override
                public void run() {
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                    } else {
                        getActivity().startActivityForResult(intent, WebActivity.TAKEPICTURE_REQUESTCODE);
                        //Toast.makeText(getActivity(), "文件路径：" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                        //WebActivity.res.setResult(file.getAbsolutePath());
                        //WebActivity.photoPath = file.getAbsolutePath();
                        //WebActivity.res.setStatus(-1);
                    }
                }
            });
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        dismiss();
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static synchronized AutoSignFragment getAutoSignInstance() {
        if (autoSignFragment == null) {
            autoSignFragment = new AutoSignFragment();
        }
        return autoSignFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(autoSignFragment != null) {
            autoSignFragment = null;
        }
        /*RxBus rxBus =  MSApplication.getRxBus();
        rxBus.send(AutoSignService.SERVICE_START_COUNT);*/
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mSignOrders != null && mSignOrders.size() > 0) {
            AutoSignAdapter signAdapter = new AutoSignAdapter(mSignOrders, getActivity());
            signAdapter.setmOnItemClickListener(this);
            mAutoSignView.setHasFixedSize(true);
            mAutoSignView.setLayoutManager(new LinearLayoutManager(getContext()));
            mAutoSignView.setItemAnimator(new DefaultItemAnimator());
            ViewGroup.LayoutParams params = mAutoSignView.getLayoutParams();
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            int height = wm.getDefaultDisplay().getHeight();
            params.height = mSignOrders.size() * height / 8;
            mAutoSignView.setLayoutParams(params);
            mAutoSignView.setAdapter(signAdapter);
        }else{
            dismiss();
        }
    }

    @Override
    public int provideContentRes() {
        return R.layout.fragment_autosign;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    @Override
    public void onItemClick(int position) {
        //在这里调用自动签到的代码
        final AutoSignOrder order = mSignOrders.get(position);
        OrderUpdatingRequest signRequest = new OrderUpdatingRequest();
        signRequest.setTicketid(order.getTicketid());
        signRequest.setAction(OrderAction.SIGININ.getValue());
        ServiceGenerator.createService(OrderAPI.class).updateOrder(order.getTicketid(), OrderAction.SIGININ.getValue(), signRequest)
                // Started in onStart(), running until in onStop()
                //.compose(fragment.<Res>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .doOnTerminate(new Action0() {
                    @Override
                    public void call() {
                        //webActivity.processDismiss();
                                            /*if(_subscription != null) {
                                                _subscription.unsubscribe();
                                                _subscription = null;
                                            }*/
                    }
                })
                .subscribe(new NetworkObserver<Res>() {
                    @Override
                    public void onSuccess(Res result) {
                        //webActivity.processDismiss();
                        if(result.getEcode() != 0){
                            Toast.makeText(getActivity(), "自动签到失败，请手动签到，上传照片", Toast.LENGTH_SHORT).show();
                            Intent photoSignIntent = new Intent(AutoSignFragment.this.getActivity(), SignInCameraActivity.class);
                            photoSignIntent.putExtra("ticketid", order.getTicketid());
                            AutoSignFragment.this.getActivity().startActivity(photoSignIntent);
                        }else{
                            Toast.makeText(getActivity(), "签到成功", Toast.LENGTH_SHORT).show();
                            //签到成功，将signedLatlng值为null,
                            signedLatLng = null;
                            currentTime = 0;
                            //刷新页面
                            List<Activity> activityList = FBaseActivity.getActivites();
                            for(Activity a : activityList){
                                if(a instanceof MainActivity){
                                    ((MainActivity) a).onPageSelected(MainActivity.PAGE_ACTIVE_ORDER, true);
                                }else{
                                    ((FBaseActivity)a).setResult(Activity.RESULT_CANCELED);
                                    ((FBaseActivity)a).defaultFinish();
                                }
                            }
                        }
                        dismiss();
                    }

                    @Override
                    public void onFailure(String tip) {
                        //webActivity.processDismiss();
                        Toast.makeText(getActivity(), "自动签到失败，请手动签到，上传照片", Toast.LENGTH_SHORT).show();
                        Intent photoSignIntent = new Intent(AutoSignFragment.this.getActivity(), SignInCameraActivity.class);
                        photoSignIntent.putExtra("ticketid", order.getTicketid());
                        AutoSignFragment.this.getActivity().startActivity(photoSignIntent);
                        dismiss();
                    }
                });
    }

    private void autoSign(){

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //记下当前签到的位置和时间
        signedLatLng = AutoSignService.mLatLng;
        currentTime = System.currentTimeMillis();
    }
}
